package www.lagou.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import www.lagou.entity.Account;
import www.lagou.utils.DateUtils;
import www.lagou.utils.DruidUtils;

import java.sql.SQLException;

public class AccountDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    /**
     * 查询剩余的钱还有多少
     * @param card
     * @return
     * @throws SQLException
     */
    public Double money(String card) throws SQLException {
        String sql="select balance from account where card=?";
        Object[] param={card};
        Double query = (Double)qr.query(sql, new ScalarHandler<>(), param);
        return query;

    }

    /**
     * 执行转账操作
     * @param user1
     * @param user2
     * @param blance
     * @return
     * @throws SQLException
     */
    public boolean transfer(Account user1, Account user2, Double blance) throws SQLException {
        //1.获取QueryRunner

        String card1 = user1.getCard();
        String card2 = user2.getCard();

        if (user1.getBalance()<5000.00){
            System.out.println("余额不足");
            return false;
        }
        //2.编写SQL
        String sql="update account set balance=balance+?where card=?";
        Object[] param ={blance,card2};
        //3.执行增加操作
        int result=qr.update(sql,param);

        String sql2="update account set balance=balance-?where card=?";
        Object[] param2={blance,card1};
        int result2=qr.update(sql2,param2);

        if(result>0&&result2>0){
            String sql3="insert into Transaction values(null,?,'转出',?,?)";
            String sql4="insert into Transaction values(null,?,'转入',?,?)";
            Object[] param3={user1.getCard(),blance, DateUtils.getDateFormart()};
            Object[] param4={user2.getCard(),blance, DateUtils.getDateFormart()};
            qr.update(sql3,param3);
            qr.update(sql4,param4);
            return  true;
        }else {
            return  false;
        }


    }
}
